//
//  PrintViewController.m
//  quickBatchManager
//
//  Created by jack on 15/11/24.
//  Copyright © 2015年 jack. All rights reserved.
//

#import "PrintViewController.h"

@interface PrintViewController ()
{
    NSMutableArray *datas;
    NSInteger _index;
    BOOL isQR;
}
@end

@implementation PrintViewController

- (void)viewDidLoad {
    [super viewDidLoad];
  
    
  
}


-(void)initData
{
    datas = [PrintModel searchWithWhere:nil];
     NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    isQR = [defaults boolForKey:@"isQR"];
    _isQRSWitch.on = isQR;
    
}


-(void)initUI
{
    [_printBtn bk_whenTapped:^{
        [self dismissViewControllerAnimated:YES completion:nil];
    }];
    
    [_comfirmBtn bk_whenTapped:^{
        if([_inputTextField.text isValid])
        {
            PrintModel *model = [[PrintModel alloc] init];
            model.content = _inputTextField.text;
            model.isSelect = NO;
            [PrintModel insertToDB:model];
             datas = [PrintModel searchWithWhere:nil];
            [_mTableVIew reloadData];
        }
    }];
    
    [_isQRSWitch addTarget:self action:@selector(switchAction:) forControlEvents:UIControlEventValueChanged];
    
    _mTableVIew.dataSource  = self;
    _mTableVIew.delegate = self;
    
}

-(void)switchAction:(id)sender
{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setBool:_isQRSWitch.on forKey:@"isQR"];
    [defaults synchronize];
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [datas count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
   static NSString *CMainCell = @"defaultCell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CMainCell];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1  reuseIdentifier: CMainCell];
    }
  
    PrintModel *model = [datas objectAtIndex:indexPath.row];
    cell.textLabel.text = model.content;
    if(model.isSelect)
    {
        cell.accessoryType = UITableViewCellAccessoryCheckmark;
    }else
    {
        cell.accessoryType = UITableViewCellAccessoryNone;
    }

    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    // 取消前一个选中的，就是单选啦
    NSIndexPath *lastIndex = [NSIndexPath indexPathForRow:_index inSection:0];
    UITableViewCell *lastCell = [tableView cellForRowAtIndexPath:lastIndex];
    lastCell.accessoryType = UITableViewCellAccessoryNone;
     PrintModel *lastModel = [datas objectAtIndex:_index];
    lastModel.isSelect = NO;
    [lastModel updateToDB];

    _index = indexPath.row;
    PrintModel *model = [datas objectAtIndex:indexPath.row];
     model.isSelect = YES;
    [model updateToDB];
    
    
    [_mTableVIew reloadData];
}






@end
